package com.ribbon;

import com.netflix.hystrix.HystrixObservableCommand;
import org.springframework.web.client.RestTemplate;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by qhe on 2018/7/26.
 *
 * 继承方式实现响应式的封装命令
 */
public class UserObservableCommand extends HystrixObservableCommand<User> {

    private RestTemplate restTemplate;
    private Long id;

    public UserObservableCommand(Setter setter,RestTemplate restTemplate,Long id){
        super(setter);
        this.restTemplate = restTemplate;
        this.id = id;
    }

    @Override
    protected Observable<User> construct() {
        return Observable.create(new Observable.OnSubscribe<User>(){

            @Override
            public void call(Subscriber<? super User> observer) {
                if(!observer.isUnsubscribed()){
                    User user = restTemplate.getForObject("http",User.class,id);
                    observer.onNext(user);
                    observer.onCompleted();
                }
            }
        });
    }
}
